<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getReportListApi, printReportApi } from '#/api';
import { downloadFileFromBlob } from '@vben/utils';
import { MdiPrinter, MdiRefresh } from '@vben/icons';
import { confirmModal } from '#/components';

interface RowType {
  ID: string;
  ProductOrderCode: string;
  CustomerName: string;
  SerialCode: string;
  BottleCode: string;
  BottleVolume: string;
  GBName: string;
  GBCode: string;
  TechParams: string;
  TouChanDate: string;
  TouChanPersonName: string;
  CompletedDate: string;
  FillPressure: string;
  minPressure: string;
  AnalyseDate: string;
  AnalystName: string;
  ExpirationDate: string;
  QuotationCode: string;
  Note: string;
}

const loadingV = ref(false); // 记录当前是否进入loading状态

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { fixed: 'left', field: 'checkbox', type: 'checkbox', title: '全选', width: 75 },
    { fixed: 'left', field: 'ID', title: 'ID', width: 90 },
    { field: 'ProductOrderCode', title: '生产单号', width: 130 },
    { field: 'CustomerName', title: '客户名称', width: 170 },
    { field: 'SerialCode', title: '流水号', width: 130 },
    { field: 'BottleCode', title: '气瓶编号', width: 130 },
    // { field: 'BottleVolume', title: '气瓶容积', width: 200 },
    { field: 'GBName', title: '标物名称', width: 250 },
    { field: 'GBCode', title: '标物代码', width: 130 },
    { field: 'TechParams', title: '技术参数', width: 300 },
    // { field: 'TouChanDate', title: '投产日期', width: 200 },
    // { field: 'TouChanPersonName', title: '投产人员', width: 200 },
    // { field: 'CompletedDate', title: '完成日期', width: 200 },
    // { field: 'FillPressure', title: '充装压力', width: 200 },
    // { field: 'minPressure', title: '最小压力', width: 200 },
    // { field: 'AnalyseDate', title: '分析日期', width: 200 },
    // { field: 'AnalystName', title: '分析人员', width: 200 },
    // { field: 'ExpirationDate', title: '有效期至', width: 200 },
    { field: 'QuotationCode', title: '报价单号', width: 130 },
    // { field: 'Note', title: '备注信息', width: 200 },
    // { field: 'matchRes', title: '匹配结果', width: 200 },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const result = await getReportListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
        });
        // 如果result.message不为ok或undefined，则使用message显示result.message
        if (result.message === '未查询到匹配的数据') {
          message.info(result.message);
        } else if (result.message !== 'ok' && result.message !== undefined) {
          message.error(result.message);
        }

        // // 转译数据
        // const testItemsOptionsMap = testItemsOptions.reduce((acc: any, cur: any) => {
        //   acc[cur.value] = cur.label;
        //   return acc;
        // }, {});
        result.items = result.items.map((item: any) => {
          return {
            ...item,
            CompletedDate: item.CompletedDate ? item.CompletedDate.split('T')[0] : '',
            AnalyseDate: item.AnalyseDate ? item.AnalyseDate.split('T')[0] : '',
            TouChanDate: item.TouChanDate ? item.TouChanDate.split('T')[0] : '',
          };
        });
        return result;
      },
    },
  },
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  showOverflow: false,
  pagerConfig: {},
  toolbarConfig: {
    export: true,
    refresh: true,
    refreshOptions: {
      code: 'reload',
    },
    search: true,
    zoom: true,
    custom: true,
  },
  customConfig: {
    mode: 'modal',
    checkMethod({ column }) {
      return !['checkbox', 'ID', 'ProductOrderCode'].includes(column.field);
    },
  },
  rowConfig: {
    isHover: true,
  },
  columnConfig: {
    resizeable: true,
  },
  resizeableConfig: {
    isDblClickAutoWidth: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});

/*==================================函数过程=========================================*/

async function handlePrint() {
  try {
    loadingV.value = true;
    message.loading({
      content: '数据处理中，请稍后...',
      duration: 0,
      key: 'beforePrint',
    });
    // 延迟0.5秒，确保全局loading生效，防止用户再次操作
    await new Promise((resolve) => setTimeout(resolve, 500));

    const selectedRows = await gridApi.grid.getCheckboxRecords();
    if (selectedRows.length > 0) {
      // gridApi.grid.setCheckboxRow(rows, false);
      let printRowIDs: string[] = [];
      for (const row of selectedRows) {
        printRowIDs.push(row.ID);
      }
      let response = await printReportApi(printRowIDs);
      // 创建a标签下载
      // const downloadLink = document.createElement('a');
      // downloadLink.href = URL.createObjectURL(response.blob);
      // downloadLink.download = response.fileName.toString() || 'report';
      // downloadLink.click();
      // URL.revokeObjectURL(downloadLink.href);

      // downloadFileFromUrl({
      // // 已测试可以下载
      //   source:
      //     '../public/output/WTC-0001.pdf',
      //   target: '_self',
      // })

      // 检查responseBlob是否为Blob对象
      if (response.blob instanceof Blob) {
        await message.success({
          content: '数据处理完成',
          duration: 2,
          key: 'beforePrint',
        });
        const confirmRes = await confirmModal('提示', '是否需要下载？');
        if (confirmRes) {
          let fileName: string = response.fileName.toString();
          if (response.fileName === 'UnknowFile.unknown') {
            fileName = printRowIDs.length > 1 ? '分析报告.zip' : '分析报告.docx';
          }
          downloadFileFromBlob({
            source: response.blob,
            fileName: fileName,
          });
        }
      } else {
        message.error({
          content: '返回数据类型异常！',
          key: 'beforePrint',
        });
      }
    } else {
      message.info({
        content: '请至少选择一行数据',
        key: 'beforePrint',
      });
    }
  } catch (error) {
    message.error({
      content: `出现错误：${error.message}`,
      key: 'beforePrint',
    });
  } finally {
    loadingV.value = false;
    // message.destroy('beforePrint');
  }
}

// 刷新并返回第一页
const handleReload = async () => {
  gridApi.reload();
};
</script>
<template>
  <Page v-loading="loadingV" auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2 flex items-center justify-center" type="primary" @click="handlePrint()">
          <!-- 20像素大小的图标 -->
          <MdiPrinter class="size-4" />
          打印
        </Button>
        <Button
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #0bd092"
          @click="handleReload"
        >
          <MdiRefresh class="size-4" />
          刷新
        </Button>
      </template>
    </Grid>
  </Page>
</template>
